#include "libUnitTest/UnitTestPP.hpp"
#include "libUnitTest/TestReporterStdout.hpp"

#include <string.h>

using namespace UnitTest;

static Test* find_test(const char *name)
{
   Test* index = Test::GetTestList().GetHead();
   while (index != 0) {
      if (strcmp(index->m_details.testName, name) == 0)
         return index;
      index = index->m_nextTest;
   }

   return nullptr;
}

static void usage(const char *name)
{
   fprintf(stderr, "Usage: %s [TEST]\n\n"
         "With no arguments, run all test.  Specify test case to run\n"
         "only that test without forking.  Available tests:\n\n",name);

   Test* index = Test::GetTestList().GetHead();
   while (index != 0) {
      fprintf(stderr, "%s \n", index->m_details.testName);
      index = index->m_nextTest;
   }

   fprintf(stderr, "\n");
}

int main(int argc, char const *argv[])
{
   TestReporterStdout reporter;
   TestRunner runner(reporter);
   TestResults* lResults = new TestResults(&reporter);

   if (argc == 2 && strcmp(argv[1], "--help") == 0) {
      usage(argv[0]);
      return -1;
   }


   if (argc == 2)
   {
      Test* test = find_test(argv[1]);
      if (test == nullptr)
      {
         fprintf(stderr, "unknown test: \"%s\"\n", argv[1]);
         usage(argv[0]);
         return -1;
      }
      Timer testTimer;

      lResults->OnTestStart(test->m_details);
      test->Run();

      double const testTimeInMs = testTimer.GetTimeInMs();
      lResults->OnTestFinish(test->m_details, static_cast< float >(testTimeInMs / 1000.0));

      return 0;

   }

   return UnitTest::RunAllTests();
}
